<?php

namespace App\Kuafu\Product\Controller\B;

use App\Exceptions\BaseException;
use App\Exceptions\CustomValidateException;
use App\Kuafu\Common\Service\CommonService;
use App\Kuafu\Product\Enum\CodeEnum;
use App\Kuafu\Product\Enum\ProductCodeEnum;
use App\Kuafu\Product\Exceptions\ProductException;
use App\Kuafu\Product\Service\ProductService;
use App\Kuafu\Product\Validate\ProductNewValidate;
use App\Kuafu\Product\Validate\ProductValidate;
use App\Kuafu\ProductMenu\Exceptions\ProductMenuException;
use App\Kuafu\Shop\Exceptions\ShopException;
use App\Kuafu\User\Exceptions\UserException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Kuafu\Base\Controller\BaseController;
use App\Kuafu\Base\Enum\BaseCodeEnum;
use Illuminate\Validation\ValidationException;
use PHP_CodeSniffer\Util\Common;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class ProductController extends BaseController
{

    public function addProduct(Request $request)
    {
        $type = $request->type ?: 0;
        //参数校验
        $valid = ProductValidate::addProduct($request);
        if ($valid) {
            return $this->fail(ProductCodeEnum::ERR_PRODUCT_INSERT, $valid);
        }

        if ($request->type == CodeEnum::PRODUCT_TYPE_PACKAGE) {
            //检验套餐数据
            $valid = ProductValidate::checkPackageData($request);
            if ($valid) {
                return $this->fail(ProductCodeEnum::ERR_PRODUCT_INSERT, $valid);
            }
            ProductService::checkPackageTotalPrice($request->productList, $request->price, $request->vipPrice);
        }
        ProductService::addProduct($request, $type);
        return $this->success();
    }

    /**
     * 获取菜品列表
     * @param Request $request
     * @return JsonResponse
     */
    public function getProductList(Request $request)
    {
        $name       = (string)$request->get('name', '');
        $kind       = (int)$request->get('kind', 0);
        $categoryId = (int)$request->get('categoryId', 0);
        $pageSize   = (int)$request->get('pageSize', 20);
        $pageNum    = (int)$request->get('pageNum', 1);
        $brandId    = $request->header('brandId');
        $menuId     = 0;
        return $this->success(ProductService::getProductList($brandId, $categoryId, $name, $pageSize, $pageNum,
            $menuId, $kind));
    }

    /**
     * 根据id获取产品详情
     * @param Request $request
     * @return JsonResponse
     */
    public function getProductInfoById(Request $request)
    {
        if (empty($request->productId)) {
            return $this->fail(BaseCodeEnum::ERR_400009, '非法数据,参数错误');
        }
        $productInfoById = ProductService::getProductInfoById($request->productId);
        $return          = null;
        if ($productInfoById) {
            $return              = $productInfoById;
            $return['price']     = $return['price'] ?: '';
            $return['vipPrice']  = $return['vipPrice'] ?: '';
            $return['costPrice'] = $return['costPrice'] ?: '';
            $return['imageUrl']  = CommonService::joinImageUrl($return['imageUrl']);
        }
        return $this->success($return);
    }


    /**
     * 删除产品(软删除)
     * @param Request $request
     * @return JsonResponse
     */
    public function deletedProduct(Request $request)
    {
        if (empty($request->productId)) {
            return $this->fail(BaseCodeEnum::ERR_400009, '非法数据,参数错误');
        }
        ProductService::deletedProduct($request->productId);
        return $this->success();
    }


    /**
     * 修改菜品基本信息
     * @param Request $request
     * @return JsonResponse
     */
    public function setProductById(Request $request)
    {
        $type = $request->type ?: 0;
        if (empty($request->productId)) {
            return $this->fail(BaseCodeEnum::ERR_400009, '非法数据,参数错误');
        }
        $valid = ProductValidate::addProduct($request);
        if ($valid) {
            return $this->fail(ProductCodeEnum::ERR_PRODUCT_INSERT, $valid);
        }
        if ($type == CodeEnum::PRODUCT_TYPE_PACKAGE) {
            //检验套餐数据
            $valid = ProductValidate::checkPackageData($request);
            if ($valid) {
                return $this->fail(ProductCodeEnum::ERR_PRODUCT_INSERT, $valid);
            }
            ProductService::checkPackageTotalPrice($request->productList, $request->price, $request->vipPrice);
        }
        ProductService::setProductById($request, $type);
        return $this->success();
    }

    public function setProductStatus(Request $request)
    {
        if (empty($request->productId)) {
            return $this->fail(BaseCodeEnum::ERR_400009, '非法数据,参数错误');
        }
        if (!in_array($request->status, [0, 1, 2])) {
            return $this->fail(ProductCodeEnum::ERR_PRODUCT_STATUS);
        }
        ProductService::setProductStatus($request);
        return $this->success();
    }


    public function setProductIsHot(Request $request)
    {
        if (empty($request->productId)) {
            return $this->fail(BaseCodeEnum::ERR_400009, '非法数据,参数错误');
        }
        if (!in_array($request->isHot, [0, 1])) {
            return $this->fail(ProductCodeEnum::ERR_PRODUCT_STATUS);
        }
        ProductService::setProductIsHot($request);
        return $this->success();
    }

    public function setProductIsRecommend(Request $request)
    {
        if (empty($request->productId)) {
            return $this->fail(BaseCodeEnum::ERR_400009, '非法数据,参数错误');
        }
        if (!in_array($request->isRecommend, [0, 1])) {
            return $this->fail(ProductCodeEnum::ERR_PRODUCT_STATUS);
        }
        ProductService::setProductIsRecommend($request);
        return $this->success();
    }

    /**
     * 菜品绑定菜单（全量更新）
     * @param Request $request
     * @return JsonResponse
     */
    public function bindMenu(Request $request)
    {
        $productMenuId = $request->post('productMenuId');
        $productIds    = $request->post('productIds');

        $valid = ProductValidate::bindMenu($request->all());
        if ($valid) {
            return $this->fail(ProductCodeEnum::ERR_PRODUCT_PARAM, $valid);
        }
        ProductService::bindMenuIds($productIds, $productMenuId);

        return $this->success();
    }

    /**
     * 添加菜品
     *
     * @param Request $request
     * @return JsonResponse
     * @throws ProductException
     * @throws ValidationException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function insert(Request $request): JsonResponse
    {
        $brandId = $request->header('brandId', 0);
        $shopId  = $request->header('shopId', 0);
        ProductService::insert($shopId, $brandId, ProductNewValidate::webInsertValidate($request->all()));
        return $this->success();
    }

    /**
     * 编辑菜品
     *
     * @param Request $request
     * @param int $productId
     * @return JsonResponse
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ProductException
     * @throws ValidationException
     */
    public function update(Request $request, int $productId): JsonResponse
    {
        $brandId = $request->header('brandId', 0);
        $shopId  = $request->header('shopId', 0);
        ProductService::update(
            $shopId,
            $brandId,
            ProductNewValidate::updateValidate($request->merge(["id" => $productId])->all())
        );
        return $this->success();
    }

    /**
     * 菜品详情
     *
     * @param Request $request
     * @param int $productId
     * @return JsonResponse
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ProductException|CustomValidateException
     */
    public function detail(Request $request, int $productId): JsonResponse
    {
        $brandId = $request->header('brandId', 0);
        $shopId  = $request->header('shopId', 0);
        $params  = ProductNewValidate::detailValidate($request->merge(["id" => $productId])->all());
        return $this->success(ProductService::detail($productId, $shopId, $brandId, $params));
    }

    /**
     * @param Request $request
     * @param int $productId
     * @return JsonResponse
     * @throws BaseException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ProductException
     * @throws UserException
     * @throws ValidationException
     */
    public function delete(Request $request, int $productId): JsonResponse
    {
        $shopId  = $request->header("shopId", 0);
        $brandId = $request->header("brandId", 0);

        $params = ProductNewValidate::webDeleteValidate($request->merge(["id" => $productId])->all());
        ProductService::delete($shopId, $brandId, $params);
        return $this->success();
    }

    /**
     * 修改菜品状态
     *
     * @param Request $request
     * @param int $productId
     * @return JsonResponse
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ProductException
     * @throws ProductMenuException
     * @throws ShopException
     * @throws ValidationException
     * @throws BaseException
     */
    public function status(Request $request, int $productId): JsonResponse
    {
        $shopId  = $request->header("shopId", 0);
        $brandId = $request->header("brandId", 0);
        $params  = ProductNewValidate::webStatusValidate($request->merge(["id" => $productId])->all());
        ProductService::webStatus($shopId, $brandId, $params);
        return $this->success();
    }


    /**
     * 查询菜品不同门店价格数据
     * @param Request $request
     * @param int $productId
     * @return JsonResponse
     */
    public function priceData(Request $request, int $productId): JsonResponse
    {
        return $this->success(ProductService::getPriceData($productId));
    }

    /**
     * 菜品详情
     *
     * @param Request $request
     * @param int $productId
     * @return JsonResponse
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ProductException
     * @throws ValidationException
     */
    public function detailFromApplet(Request $request, string $productId): JsonResponse
    {
        $brandId = $request->header('brandId', 1);
        $shopId  = $request->header('shopId', 0);

        $productExp = explode('-', $productId);
        $productId  = $productExp[0];
        $productNum = $productExp[1] ?? 1;
        ProductNewValidate::detailValidate($request->merge(["id" => $productId])->all());

        $info        = ProductService::detailFromApplet($productId, $shopId, $brandId);
        $info['num'] = (int)$productNum;

        return $this->success($info);
    }

}
